package chalmers.game.subterranean.model.items;

import chalmers.game.subterranean.event.Bus;
import chalmers.game.subterranean.event.events.ClockTickEvent;
import chalmers.game.subterranean.event.events.RestartGameEvent;
import chalmers.game.subterranean.event.events.player.SetTorchSizeEvent;
import chalmers.game.subterranean.util.options.PlayerValues;
import chalmers.game.subterranean.util.options.Variables;
import chalmers.game.subterranean.util.options.WorldValues;
import com.google.common.eventbus.Subscribe;
import lombok.Getter;
import lombok.Setter;
import org.apache.log4j.Logger;

/**
 * User: Mikael Friederici Date: 2014-05-18 Time: 23:32
 */
public class Torch {

  private @Setter
  @Getter
  double burnTime;
  private double burnTimeTimer;
  private int tickCounter = 0;
  private @Getter
  boolean isLit;
  private Double radius;
  private Double changeRadius;
  private int secCounter = 0;

  private static final Logger logger = Logger.getLogger("subLog");
  public final String name = "Torch";

  // TODO fix this mess.. :)
  public Torch(double burnTime) {
    Bus.INSTANCE.register(this);
    this.burnTime = burnTime;
  }

  @Subscribe
  public void clockTickHandler(ClockTickEvent event) {
    if (isLit) {
      tickCounter++;
      if (tickCounter == Variables.CLOCK_TICKS_PER_SECOND) {
        tickCounter = 0;
        updateTorch();
      }
    }
  }

  public void litTorch() {
    burnTimeTimer = burnTime;
    radius = PlayerValues.TORCH_DEFAULT_RADIUS;
    isLit = true;
    changeRadius = (radius / burnTime) * PlayerValues.TORCH_UPDATE_INTERVAL;
    logger.info("Torch is lit");
    Bus.INSTANCE.post(new SetTorchSizeEvent(radius));
  }

  public void extinguishTorch() {
    isLit = false;
      Bus.INSTANCE.post(new SetTorchSizeEvent(WorldValues.GAME_RESOLUTION_WIDTH * 1.2));
    logger.info("Torch is extinguished");
  }

  private void updateTorch() {
    burnTimeTimer--;
    secCounter++;
    if (secCounter == PlayerValues.TORCH_UPDATE_INTERVAL
        || secCounter > PlayerValues.TORCH_UPDATE_INTERVAL) {
      secCounter = 0;
      radius = radius - changeRadius;
      Bus.INSTANCE.post(new SetTorchSizeEvent(radius));
    }
    if (burnTimeTimer == 0) {
        logger.info("Torch extinguished!");
      Bus.INSTANCE.post(new SetTorchSizeEvent(0.0));
      Bus.INSTANCE.post(new RestartGameEvent());
    }
  }

  @Override
  public String toString() {
    return name;
  }
}
